/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.ce.managedbeans;

import com.bionic.ce.entities.Systemacc;
import com.bionic.ce.entitybeans.systemacc.SystemaccFacadeLocal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean(name = "systemAccManagedBean")
@SessionScoped
public class SystemAccManagedBean implements Serializable {

    public SystemAccManagedBean() {
    }
    public Systemacc systemAcc = new Systemacc();
    @EJB
    private SystemaccFacadeLocal systemAccEJB;
    List<Systemacc> systemAccList = new ArrayList<Systemacc>();
    @ManagedProperty("#{userManagedBean}")
    private UserManagedBean userMB;
    @ManagedProperty("#{currencyManagedBean}")
    private CurrencyManagedBean currencyMB;
    @ManagedProperty("#{bankAccManagedBean}")
    private BankAccManagedBean bankAccMB;
    Integer amount;

    public BankAccManagedBean getBankAccMB() {
        return bankAccMB;
    }

    public void setBankAccMB(BankAccManagedBean bankAccMB) {
        this.bankAccMB = bankAccMB;
    }

    public CurrencyManagedBean getCurrencyMB() {
        return currencyMB;
    }

    public void setCurrencyMB(CurrencyManagedBean currencyMB) {
        this.currencyMB = currencyMB;
    }

    public Systemacc getSystemAcc() {
        systemAcc = new Systemacc();
        return systemAcc;
    }

    public void setSystemAcc(Systemacc systemAcc) {
        this.systemAcc = systemAcc;
    }

    public SystemaccFacadeLocal getSystemAccEJB() {
        return systemAccEJB;
    }

    public void setSystemAccEJB(SystemaccFacadeLocal systemAccEJB) {
        this.systemAccEJB = systemAccEJB;
    }

    public List<Systemacc> getSystemAccList() {
        return systemAccList;
    }

    public void setSystemAccList(List<Systemacc> systemAccList) {
        this.systemAccList = systemAccList;
    }

    public UserManagedBean getUserMB() {
        return userMB;
    }

    public void setUserMB(UserManagedBean userMB) {
        this.userMB = userMB;
    }

    public Integer getAmount() {
        return amount = null;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }
    
    //создание счёта в системе
    public String doCreateSystemAcc() {
        String page = null;
        boolean isOK = (!systemAccEJB.findByUserIdAndCurrency(userMB.getUser().getId(), systemAcc.getCurrency().getShortName()).isEmpty());
        if (isOK) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "System account error: ", "you can`t have more than one account in system in " + systemAcc.getCurrency().getShortName()));
        } else {
            systemAcc.setUserid(userMB.getUser());
            systemAcc.setAmount(0.0);
            systemAcc.setStatus("OPEN");
            systemAccEJB.create(systemAcc);
            page = doShowList();
        }
        return page;
    }
    
    //обновление данных счёта в системе
    public String doUpdateSystemAcc() {
        systemAccEJB.edit(systemAcc);
        return doShowList();
    }

    //возвращает страницу со списком счётов в системе для текущего пользователя
    public String doShowList() {
        systemAccList = systemAccEJB.findByUserIdAndCurrency(userMB.getUser().getId(), null);
        return "/pages/systemacc/systemaccountsinfo.xhtml?faces-redirect=true";
    }

    //переход на страницу доступных по валюте банковских счётов для пополнения выбраного счёта в системе
    public String goToDepositSelected() {
        String page = null;
        bankAccMB.bankAccList = bankAccMB.getBankAccEJB().findByUserIdAndCurrency(userMB.getUser().getId(), systemAcc.getCurrency().getShortName());
        if (bankAccMB.bankAccList.isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "System account error: ", "you don`t have any bank account in " + systemAcc.getCurrency().getShortName()));
        } else {
            page = "/pages/systemacc/systemaccdeposit.xhtml?faces-redirect=true";
        }
        return page;
    }

    //переход на страницу доступных по валюте банковских счётов для перевода денег с выбраного счёта в системе
    public String goToWithdrawSelected() {
        String page = null;
        bankAccMB.bankAccList = bankAccMB.getBankAccEJB().findByUserIdAndCurrency(userMB.getUser().getId(), systemAcc.getCurrency().getShortName());
        if (bankAccMB.bankAccList.isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "System account error: ", "you don`t have any bank account in " + systemAcc.getCurrency().getShortName()));
        } else {
            page = "/pages/systemacc/systemaccwithdraw.xhtml?faces-redirect=true";
        }
        return page;
    }

    //пополнение выбранного ранее счёта в системе на указанную сумму
    public String doDepositSelected() {
        if (amount >= 0) {
            systemAcc.setAmount(systemAcc.getAmount() + amount);
            return doUpdateSystemAcc();
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Deposit error: ", "depositing sum must be positive"));
            return null;
        }
    }
    //снятие денег с выбранного ранее счёта в системе
    public String doWithdrawSelected() {
        if (amount > systemAcc.getAmount()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Withdraw error: ", "you don`t have such amount in your account. (Current balance is: " + systemAcc.getAmount() + " " + systemAcc.getCurrency().getShortName() + ")"));
            return null;
        } else if (amount >= 0) {
            systemAcc.setAmount(systemAcc.getAmount() - amount);
            System.out.println("SELECTED " + systemAcc);
            return doUpdateSystemAcc();
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Withdraw error: ", "withdrawing sum must be positive"));
            return null;
        }
    }
    
    public String goToAddSystemAcc() {
        systemAcc=new Systemacc();
        return "/pages/systemacc/registersystemacc.xhtml?faces-redirect=true";
    }
}
